﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Quartz;
using ServiceContainer.Commom;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Enums;
using YouWei.Infrastructure.Service;
using YouWei.Utility;
using YouWei.Utility.Logging;

namespace ServiceContainer.Jobs
{


    /// <summary>
    /// 短信发送状态监控作业
    /// </summary>
  
    public class SmsMonitorJob : IJob
    {

        private static DateTime dtStartTime = DateTime.Now;
        private static string TestPersons = "13436300382";
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                DoWork();

            }
            catch (Exception ex)
            {
                Log4netLog.Error(101,context.JobDetail.Key+"作业出现异常,异常信息为："+ex);
            }
        }

        private void DoWork()
        {
            var svCard=new SmsCardService();

            
            var listAllAvailableCard = svCard.GetAllAvaliableCards(DateTime.Now);
            if (listAllAvailableCard.Count == 0)
            {
                return;
            }
            //只发送第一张卡片状态报告，后续需要可以对每张卡片都发送状态报告
            for (var i = 0; i < 1; i++)
            {
                var card = listAllAvailableCard[i];
                string szReport = GetCardReport(card);
                if (!string.IsNullOrEmpty(szReport) && szReport.Contains("计划发送"))
                {
                    ChannelShortMsgHelper.SendProductMsg(TestPersons, szReport);
                }
            }
        }

        public string GetCardReport(SmsCard card)
        {
            string szReturn = string.Empty;
            var svTaskTime=new SmsTaskTimeService();
            var dtNow = DateTime.Now;
            var list = svTaskTime.GetCardStatusReport(card.CardID, dtNow);
            szReturn = $"进度提醒,卡片：{card.OwnerMobile} 共{list.Count}个任务，";
            for(int i=0;i<list.Count;i++)
            {
              
                var item = list[i];
                var taskCardCount = svTaskTime.GetTaskCardCount(item.TaskID, dtNow);
                var rangeTime = (dtNow - new DateTime(dtNow.Year,dtNow.Month,dtNow.Day,item.StartTime,0,0)).TotalSeconds;
                if (item.RealSendCount > 0)
                {
                    var sendCount = item.RealSendCount/taskCardCount;
                    var nAverageTime = EConvert.ToInt(Math.Ceiling( rangeTime/ sendCount));
                    var nSpeed = Math.Ceiling((decimal)3600 / nAverageTime);
                    szReturn += $"任务{i + 1}，【{item.StartTime}-{item.EndTime}点】,计划发送【{item.SendCount/taskCardCount}】,已发送【{sendCount}】,平均【{nAverageTime}秒/个】，【{nSpeed}/小时】";
                }
            }
            return szReturn;
        }


      


    }
}
